package com.deliveryservicesystem.service.crud.impl;

import com.deliveryservicesystem.app.exceptions.NonexistentEntityException;
import com.deliveryservicesystem.app.exceptions.PreexistingEntityException;
import com.deliveryservicesystem.dataaccess.PersistenceDbManager;
import com.deliveryservicesystem.model.*;
import com.deliveryservicesystem.service.crud.SubscriptionCrudService;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * File Name: SubscriptionCrudServiceImpl.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.service.crud.impl
 * Author: Lance
 * Date: Jun 20, 2012
 * Editor:
 */
public class SubscriptionCrudServiceImpl implements SubscriptionCrudService
{

    private static final long serialVersionUID = 1L;
    private EntityManagerFactory emf = null;

    /**
     * Create the new CRUD service. Internally setting the EntityManagerFactory
     * using database details from database properties
     */
    public SubscriptionCrudServiceImpl()
    {
        PersistenceDbManager persistenceManager = PersistenceDbManager.getInstance();
        this.emf = persistenceManager.getEntityManagerFactory();
    }

    @Override
    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    @Override
    public void create(Subscription subscription) throws PreexistingEntityException, Exception
    {
        if (subscription.getProductList() == null)
        {
            subscription.setProductList(new ArrayList<Product>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Delivery deliveryNo = subscription.getDeliveryNo();
            if (deliveryNo != null)
            {
                deliveryNo = em.getReference(deliveryNo.getClass(), deliveryNo.getDeliveryNo());
                subscription.setDeliveryNo(deliveryNo);
            }
            Customer customerNo = subscription.getCustomerNo();
            if (customerNo != null)
            {
                customerNo = em.getReference(customerNo.getClass(), customerNo.getCustomerNo());
                subscription.setCustomerNo(customerNo);
            }
            Billing billingNo = subscription.getBillingNo();
            if (billingNo != null)
            {
                billingNo = em.getReference(billingNo.getClass(), billingNo.getBillingNo());
                subscription.setBillingNo(billingNo);
            }
            List<Product> attachedProductList = new ArrayList<>();
            for (Product productListProductToAttach : subscription.getProductList())
            {
                productListProductToAttach = em.getReference(productListProductToAttach.getClass(), productListProductToAttach.getProductNo());
                attachedProductList.add(productListProductToAttach);
            }
            subscription.setProductList(attachedProductList);
            em.persist(subscription);
            if (deliveryNo != null)
            {
                deliveryNo.getSubscriptionList().add(subscription);
                deliveryNo = em.merge(deliveryNo);
            }
            if (customerNo != null)
            {
                customerNo.getSubscriptionList().add(subscription);
                customerNo = em.merge(customerNo);
            }
            if (billingNo != null)
            {
                billingNo.getSubscriptionList().add(subscription);
                billingNo = em.merge(billingNo);
            }
            for (Product productListProduct : subscription.getProductList())
            {
                Subscription oldSubscriptionNoOfProductListProduct = productListProduct.getSubscriptionNo();
                productListProduct.setSubscriptionNo(subscription);
                productListProduct = em.merge(productListProduct);
                if (oldSubscriptionNoOfProductListProduct != null)
                {
                    oldSubscriptionNoOfProductListProduct.getProductList().remove(productListProduct);
                    oldSubscriptionNoOfProductListProduct = em.merge(oldSubscriptionNoOfProductListProduct);
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            if (findById(subscription.getSubscriptionNo()) != null)
            {
                throw new PreexistingEntityException("Subscription " + subscription + " already exists.", ex);
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void edit(Subscription subscription) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Subscription persistentSubscription = em.find(Subscription.class, subscription.getSubscriptionNo());
            Delivery deliveryNoOld = persistentSubscription.getDeliveryNo();
            Delivery deliveryNoNew = subscription.getDeliveryNo();
            Customer customerNoOld = persistentSubscription.getCustomerNo();
            Customer customerNoNew = subscription.getCustomerNo();
            Billing billingNoOld = persistentSubscription.getBillingNo();
            Billing billingNoNew = subscription.getBillingNo();
            List<Product> productListOld = persistentSubscription.getProductList();
            List<Product> productListNew = subscription.getProductList();
            if (deliveryNoNew != null)
            {
                deliveryNoNew = em.getReference(deliveryNoNew.getClass(), deliveryNoNew.getDeliveryNo());
                subscription.setDeliveryNo(deliveryNoNew);
            }
            if (customerNoNew != null)
            {
                customerNoNew = em.getReference(customerNoNew.getClass(), customerNoNew.getCustomerNo());
                subscription.setCustomerNo(customerNoNew);
            }
            if (billingNoNew != null)
            {
                billingNoNew = em.getReference(billingNoNew.getClass(), billingNoNew.getBillingNo());
                subscription.setBillingNo(billingNoNew);
            }
            List<Product> attachedProductListNew = new ArrayList<>();
            for (Product productListNewProductToAttach : productListNew)
            {
                productListNewProductToAttach = em.getReference(productListNewProductToAttach.getClass(), productListNewProductToAttach.getProductNo());
                attachedProductListNew.add(productListNewProductToAttach);
            }
            productListNew = attachedProductListNew;
            subscription.setProductList(productListNew);
            subscription = em.merge(subscription);
            if (deliveryNoOld != null && !deliveryNoOld.equals(deliveryNoNew))
            {
                deliveryNoOld.getSubscriptionList().remove(subscription);
                deliveryNoOld = em.merge(deliveryNoOld);
            }
            if (deliveryNoNew != null && !deliveryNoNew.equals(deliveryNoOld))
            {
                deliveryNoNew.getSubscriptionList().add(subscription);
                deliveryNoNew = em.merge(deliveryNoNew);
            }
            if (customerNoOld != null && !customerNoOld.equals(customerNoNew))
            {
                customerNoOld.getSubscriptionList().remove(subscription);
                customerNoOld = em.merge(customerNoOld);
            }
            if (customerNoNew != null && !customerNoNew.equals(customerNoOld))
            {
                customerNoNew.getSubscriptionList().add(subscription);
                customerNoNew = em.merge(customerNoNew);
            }
            if (billingNoOld != null && !billingNoOld.equals(billingNoNew))
            {
                billingNoOld.getSubscriptionList().remove(subscription);
                billingNoOld = em.merge(billingNoOld);
            }
            if (billingNoNew != null && !billingNoNew.equals(billingNoOld))
            {
                billingNoNew.getSubscriptionList().add(subscription);
                billingNoNew = em.merge(billingNoNew);
            }
            for (Product productListOldProduct : productListOld)
            {
                if (!productListNew.contains(productListOldProduct))
                {
                    productListOldProduct.setSubscriptionNo(null);
                    productListOldProduct = em.merge(productListOldProduct);
                }
            }
            for (Product productListNewProduct : productListNew)
            {
                if (!productListOld.contains(productListNewProduct))
                {
                    Subscription oldSubscriptionNoOfProductListNewProduct = productListNewProduct.getSubscriptionNo();
                    productListNewProduct.setSubscriptionNo(subscription);
                    productListNewProduct = em.merge(productListNewProduct);
                    if (oldSubscriptionNoOfProductListNewProduct != null && !oldSubscriptionNoOfProductListNewProduct.equals(subscription))
                    {
                        oldSubscriptionNoOfProductListNewProduct.getProductList().remove(productListNewProduct);
                        oldSubscriptionNoOfProductListNewProduct = em.merge(oldSubscriptionNoOfProductListNewProduct);
                    }
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = subscription.getSubscriptionNo();
                if (findById(id) == null)
                {
                    throw new NonexistentEntityException("The subscription with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Subscription subscription;
            try
            {
                subscription = em.getReference(Subscription.class, id);
                subscription.getSubscriptionNo();
            }
            catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The subscription with id " + id + " no longer exists.", enfe);
            }
            Delivery deliveryNo = subscription.getDeliveryNo();
            if (deliveryNo != null)
            {
                deliveryNo.getSubscriptionList().remove(subscription);
                deliveryNo = em.merge(deliveryNo);
            }
            Customer customerNo = subscription.getCustomerNo();
            if (customerNo != null)
            {
                customerNo.getSubscriptionList().remove(subscription);
                customerNo = em.merge(customerNo);
            }
            Billing billingNo = subscription.getBillingNo();
            if (billingNo != null)
            {
                billingNo.getSubscriptionList().remove(subscription);
                billingNo = em.merge(billingNo);
            }
            List<Product> productList = subscription.getProductList();
            for (Product productListProduct : productList)
            {
                productListProduct.setSubscriptionNo(null);
                productListProduct = em.merge(productListProduct);
            }
            em.remove(subscription);
            em.getTransaction().commit();
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public List<Subscription> findEntities()
    {
        return findSubscriptionEntities(true, -1, -1);
    }

    @Override
    public List<Subscription> findEntities(int maxResults, int firstResult)
    {
        return findSubscriptionEntities(false, maxResults, firstResult);
    }

    private List<Subscription> findSubscriptionEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Subscription.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public Subscription findById(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Subscription.class, id);
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public int count()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Subscription> rt = cq.from(Subscription.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        }
        finally
        {
            em.close();
        }
    }
}
